package com.recSystem.Utils;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.net.Socket;

/**
 * @author Legolas_PRC
 * @date 2023/4/11 17:44
 **/
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class RemoteCallUtil {
    @Value("${remote.ip}")
    private String host;
    @Value("${remote.port}")
    private int port;

    private Socket socket;

    public String send(JSONObject param) {
        try {
            socket = new Socket(host,port);
            // 输出param调用远程端口
            OutputStream os = socket.getOutputStream();
            PrintStream out = new PrintStream(os);
            out.print(param);
            out.flush();
            // 获取服务进程的输入流对象
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String tmp = null;
            StringBuilder sb = new StringBuilder();
            // 读取内容
            while ((tmp = br.readLine()) != null)
                sb.append(tmp).append('\n');
            System.out.print(sb);
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException ignored) { }
            System.out.print("远程接口调用结束.");
        }
        return null;
    }

    public static int generateTaskId(){
        return 1;
    }

}
